package com.apartment.own.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.hutool.core.bean.BeanUtil;
import com.apartment.common.annotation.CacheSelect;
import com.apartment.common.utils.DateUtils;
import com.apartment.own.domain.*;
import com.apartment.own.domain.constant.ClassNameConstants;
import com.apartment.own.request.bills.HouseWaterBillsQuery;
import com.apartment.own.response.bill.BillsResp;
import com.apartment.own.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.dreamyoung.mprelation.AutoMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.apartment.own.mapper.OwnOrdWaterBillsMapper;
import org.springframework.transaction.annotation.Transactional;

/**
 * 流水记录Service业务层处理
 *
 * @author @Dog_E
 * @date 2020-08-28
 */
@Service
@Transactional
public class OwnOrdWaterBillsServiceImpl extends ServiceImpl<OwnOrdWaterBillsMapper, OwnOrdWaterBills> implements IOwnOrdWaterBillsService {
    @Autowired
    private OwnOrdWaterBillsMapper ownOrdWaterBillsMapper;
    @Autowired
    private AutoMapper autoMapper;
    @Autowired
    private IOwnResPropertyFeeService feeService;
    @Autowired
    private IOwnOrdTenantContractService rentContractService;
    @Autowired
    private IOwnResHouseContractService houseContractService;
    @Autowired
    private IOwnAccountInstallmentService accountInstallmentService;
    @Autowired
    private IOwnAccountDetailsService accountDetailsService;

    /**
     * 查询流水记录
     *
     * @param id 流水记录ID
     * @return 流水记录
     */
    @Override
    @Cacheable
    public OwnOrdWaterBills selectOwnOrdWaterBillsById(Long id) {
        return ownOrdWaterBillsMapper.selectOwnOrdWaterBillsById(id);
    }

    /**
     * 查询流水记录列表
     *
     * @param query 流水记录
     * @return 流水记录
     */
    @Override
    public List<BillsResp> selectOwnOrdWaterBillsList(HouseWaterBillsQuery query) {
        QueryWrapper<Object> wrapper = null;
        if (query.getWaterBillStatus() == 3) {
            //流水状态已完成
            wrapper = new QueryWrapper<>()
                    //根据城市搜索
                    .eq((query.getWaterBillStatus() != null && query.getWaterBillStatus() == 3), "water_bill_status", query.getWaterBillStatus())
                    .in((query.getCityIds() != null && query.getCityIds().length != 0), "house.city_id", query.getCityIds())
                    //根据小区查询
                    .in((query.getHousingEstate() != null && query.getHousingEstate().length != 0), "house.housing_estate", query.getHousingEstate())
                    //根据整租合租查询(全部状态值为2,不做条件查询)
                    .eq((query.getHouseStatus() != null && query.getHouseStatus() != 2), "room.lease_model", query.getHouseStatus())
                    //根据收入,支出查询
                    .eq((query.getIncomeStatus() != null), "bill.in_and_out", query.getIncomeStatus())
                    //根据来源查询
                    .in((query.getSource() != null && query.getSource().length != 0), "bill.source", query.getSource())
                    //根据账单类型搜索
                    .eq((query.getWaterBillType() != null), "acin.account_type", query.getWaterBillType())
                    //根据日期搜索
                    .between((query.getBillStartTime() != null && query.getBillEndTime() != null), "bill.pay_time", query.getBillStartTime(), query.getBillEndTime())
                    //根据渠道搜索 线上线下
                    .eq((query.getChannel() != null), "bill.subscribe_way", query.getChannel())
                    //支付方式查询
                    .in((query.getPayTypes() != null && query.getPayTypes().length != 0), "bill.pay_type", query.getPayTypes())
                    //-------------------------多条件搜索--------------------------
                    .and((query.getConditionsSearch() != null), i -> i
                                    //根据小区名搜索
                                    .or().like("house.housing_estate", query.getConditionsSearch())
                                    //根据房间号搜索
                                    .or().eq("room.id", query.getConditionsSearch())
                            //todo 根据用户姓名搜索
                    );
            //----------------------------end-------------------------------
        } else {
            //流水状态待审批,已通过,已驳回
            wrapper = new QueryWrapper<>()
                    .eq((query.getWaterBillStatus() != null), "bill.water_bill_status", query.getWaterBillStatus())
                    //根据城市搜索
                    .in((query.getCityIds() != null), "house.city_id", query.getCityIds())
                    //根据小区查询
                    .in((query.getHousingEstate() != null), "house.housing_estate", query.getHousingEstate())
                    //-------------------------多条件搜索--------------------------------
                    .and((query.getConditionsSearch() != null), i -> i
                                    //根据小区名搜索
                                    .or().like("house.housing_estate", query.getConditionsSearch())
                                    //根据房间号搜索
                                    .or().eq("room.id", query.getConditionsSearch())
                            //todo 根据用户姓名搜索
                    )
                    //----------------------------end---------------------------------------
                    //根据整租合租查询
                    .eq((query.getHouseStatus() != null), "room.lease_model", query.getHouseStatus())
                    //根据收入,支出查询
                    .eq((query.getIncomeStatus() != null), "bill.in_and_out", query.getIncomeStatus())
                    //根据来源查询
                    .in((query.getSource() != null), "bill.source", query.getSource())
                    //----------------------------根据时间周期查询----------------------------
                    //根据支付时间
                    .between((query.getSearchTimeType() != null && query.getSearchTimeType() == 1), "bill.pay_time", query.getBillStartTime(), query.getBillEndTime())
                    //根据提交时间
                    .between((query.getSearchTimeType() != null && query.getSearchTimeType() == 2), "bill.submit_time", query.getBillStartTime(), query.getBillEndTime())
                    //根据审核时间
                    .between((query.getSearchTimeType() != null && query.getSearchTimeType() == 3), "bill.review_time", query.getBillStartTime(), query.getBillEndTime());
            //----------------------------------end--------------------------------
        }
        List<Map> list = ownOrdWaterBillsMapper.selectOwnOrdWaterBillsList(wrapper);
        ArrayList<BillsResp> billsResps = new ArrayList<>();
        list.forEach(x -> {
            BillsResp billsResp = BeanUtil.mapToBean(x, BillsResp.class, true);
            billsResps.add(billsResp);
        });
        return billsResps;
    }

    /**
     * 新增流水记录
     *
     * @param ownOrdWaterBills 流水记录
     * @return 结果
     */
    @Override
    public int insertOwnOrdWaterBills(OwnOrdWaterBills ownOrdWaterBills) {
        ownOrdWaterBills.setCreateTime(DateUtils.getNowDate());
        return ownOrdWaterBillsMapper.insertOwnOrdWaterBills(ownOrdWaterBills);
    }

    /**
     * 修改流水记录
     *
     * @param ownOrdWaterBills 流水记录
     * @return 结果
     */
    @Override
    public int updateOwnOrdWaterBills(OwnOrdWaterBills ownOrdWaterBills) {
        ownOrdWaterBills.setUpdateTime(DateUtils.getNowDate());
        return ownOrdWaterBillsMapper.updateOwnOrdWaterBills(ownOrdWaterBills);
    }

    /**
     * 批量删除流水记录
     *
     * @param ids 需要删除的流水记录ID
     * @return 结果
     */
    @Override
    public int deleteOwnOrdWaterBillsByIds(Long[] ids) {
        return ownOrdWaterBillsMapper.deleteOwnOrdWaterBillsByIds(ids);
    }

    /**
     * 删除流水记录信息
     *
     * @param id 流水记录ID
     * @return 结果
     */
    @Override
    public int deleteOwnOrdWaterBillsById(Long id) {
        return ownOrdWaterBillsMapper.deleteOwnOrdWaterBillsById(id);
    }

    /**
     * 根据id查看流水详情
     *
     * @param id 流水id
     * @return
     */
    @Override
    @CacheSelect
    public BillsResp selectOwnOrdWaterBillById(String id) {
        BillsResp billsResp = ownOrdWaterBillsMapper.selectOwnOrdWaterBillById(new QueryWrapper<>().eq("bill.id", id));
        //查询合同
        if (null != billsResp) {
            String billResContractId = billsResp.getBillResContractId();
            String contractSurfaceName = billsResp.getContractSurfaceName();
            if (ClassNameConstants.OWN_Bill_FK_Rent_CONTRACT.equals(contractSurfaceName)) {
                OwnOrdTenantContract rentContract = rentContractService.getById(billResContractId);
                billsResp.setRentContract(rentContract);
            } else if (ClassNameConstants.OWN_BILL_FK_HOUSE_CONTRACT.equals(contractSurfaceName)) {
                OwnResHouseContract houseContract = houseContractService.getById(billResContractId);
                billsResp.setHouseContract(houseContract);
            }
            //查询物业交割
            String houseResourceId = billsResp.getHouseResourceId();
            List<OwnResPropertyFee> listFee = feeService.list(new QueryWrapper<OwnResPropertyFee>().eq("foreign_id", houseResourceId));
            billsResp.setPropertyFee(listFee);
            //查询账单分期详情
            List<OwnAccountInstallment> accountInstallments = accountInstallmentService.list(new QueryWrapper<OwnAccountInstallment>().eq("contract_id", billsResp.getBillResContractId()));
            billsResp.setAccountInstallments(accountInstallments);
            //查询账单详情
            OwnAccountInstallment ownAccountInstallment = accountInstallments.get(0);
            OwnAccountDetails accountDetail = accountDetailsService.getOne(new QueryWrapper<OwnAccountDetails>().eq("id", ownAccountInstallment.getAccountDetailsId()));
            billsResp.setAccountDetails(accountDetail);
        }
        return billsResp;
    }
}
